import { _decorator, Component, Node, Prefab, instantiate, Animation, tween, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('FMMN_gengduo')
export class FMMN_gengduo extends Component {
    @property(Prefab)
    private prefabNode: Prefab = null!;

    @property(Node)
    private spawnParent: Node = null!;

    private activeNodes: Node[] = [];
    private maxNodes: number = 10;

    onLoad() {
        this.node.on(Node.EventType.TOUCH_END, this.onButtonClick, this);
    }

    private onButtonClick() {
        // 限制最大数量
        if (this.activeNodes.length >= this.maxNodes) {
            this.activeNodes[0].destroy();
            this.activeNodes.shift();
        }

        // 实例化预制体
        const newNode = instantiate(this.prefabNode);
        newNode.setPosition(Vec3.ZERO);
        this.spawnParent.addChild(newNode);
        this.activeNodes.push(newNode);

        // 播放淡入动画
        this.playFadeIn(newNode)
            .then(() => {
                // 淡入完成后停留1秒
                return new Promise(resolve => {
                    this.scheduleOnce(resolve, 1);
                });
            })
            .then(() => {
                // 开始淡出
                this.playFadeOut(newNode);
            });
    }

    private playFadeIn(node: Node): Promise<void> {
        return new Promise(resolve => {
            const anim = node.getComponent(Animation);
            if (anim && anim.getState('FadeIn')) {
                anim.play('FadeIn');
                anim.once(Animation.EventType.FINISHED, resolve);
                return;
            }

            // 使用tween实现淡入
            node.opacity = 0;
            tween(node)
                .to(0.3, { opacity: 255 })
                .call(resolve)
                .start();
        });
    }

    private playFadeOut(node: Node) {
        const anim = node.getComponent(Animation);
        if (anim && anim.getState('FadeOut')) {
            anim.play('FadeOut');
            anim.once(Animation.EventType.FINISHED, () => {
                this.removeNode(node);
            });
            return;
        }

        // 使用tween实现淡出
        tween(node)
            .to(0.3, { opacity: 0 })
            .call(() => {
                this.removeNode(node);
            })
            .start();
    }

    private removeNode(node: Node) {
        const index = this.activeNodes.indexOf(node);
        if (index !== -1) {
            this.activeNodes.splice(index, 1);
        }
        node.destroy();
    }
}